// pages/setting/setting.js
// 导入封装通用模块方法
import { toast, modal } from '../../utils/extendApi';
// 导入本地存储 api
import { setStorage, clearStorage, getStorage } from '../../utils/storage';
import { reqUserInfo, updateUserInfo } from '../../api/user'
import { getClassList } from '../../api/clazz'
Page({

  data: {
    userName: "",
    classesIndex: "",
    classesIds: [],
    classesArray: [],
    nickName: "",
    email: "",
    phonenumber: "",
    sexIndex: "",
    sexArray: ['男', '女', '保密'],
    isEditing: false,
    editingField: '',
    tempValue: '',
  },
  onUsernameChange: function (e) {
    const value = e.detail.value;
    this.setData({
      tempValue: value,
      userName: value
    });
  },
  editUserName() {
    this.setData({
      isEditing: true,
      editingField: 'userName',
      tempValue: this.data.userName
    });
  },
  bindClassChange: function (e) {
    this.setData({
      isEditing: true,
      editingField: 'class',
      classesIndex: e.detail.value
    });
  },
  onNicknameChange: function (e) {
    const value = e.detail.value;
    this.setData({
      tempValue: value,
      nickName: value
    });
  },
  editNickName() {
    this.setData({
      isEditing: true,
      editingField: 'nickName',
      tempValue: this.data.nickName
    });
  },
  onEmailChange: function (e) {
    const value = e.detail.value;
    this.setData({
      tempValue: value,
      email: value
    });
  },
  editEmail() {
    this.setData({
      isEditing: true,
      editingField: 'email',
      tempValue: this.data.email
    });
  },
  onPhonenumberChange: function (e) {
    const value = e.detail.value;
    this.setData({
      tempValue: value,
      phonenumber: value
    });
  },
  editPhonenumber() {
    this.setData({
      isEditing: true,
      editingField: 'phonenumber',
      tempValue: this.data.phonenumber
    });
  },
  bindSexChange: function (e) {
    this.setData({
      isEditing: true,
      editingField: 'sex',
      sexIndex: e.detail.value
    });
  },
  // 获取用户信息
  getUserInfo() {
    // 获取本地存储的userId，classesId
    let userId = getStorage('userInfo').userId
    let storage_classesIndex = getStorage('classInfo').classesIndex
    // 获取班级列表
    getClassList((res) => {
      if (res != null) {
        // 处理班级列表数据
        const classesArray = res.data.slice(2).map(item => item.classesName);
        const classesIds = res.data.slice(2).map(item => + item.classesId);
        this.setData({
          classesArray: classesArray,
          classesIds: classesIds,
          classesIndex: storage_classesIndex
        });
      }
    });

    if (!userId) {
      toast({
        title: '请先登录',
        icon: 'none'
      })
      return;
    }
    reqUserInfo(userId, (res) => {
      this.setData({
        userName: res.data.userName,
        nickName: res.data.nickName,
        email: res.data.email ? res.data.email : '',
        phonenumber: res.data.phonenumber ? res.data.phonenumber : '',
        sexIndex: res.data.sex
      })
    })
  },
  confirmEdit() {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const phoneNumberRegex = /^1\d{10}$/;
    let tempValue = this.data.tempValue;
    let isValid = true;

    if (this.data.email != '') {
      isValid = emailRegex.test(this.data.email);
      if (!isValid) {
        // 添加提示：邮箱格式不正确
        toast({
          title: '邮箱地址格式不正确',
          icon: 'none'
        })
        return;
      }
    } else if (this.data.editingField === 'phonenumber') {
      isValid = phoneNumberRegex.test(this.data.phonenumber);
      if (!isValid) {
        // 添加提示：手机号格式不正确
        toast({
          title: '手机格式不正确',
          icon: 'none'
        })
        return;
      }
    }
    this.setData({
      [this.data.editingField]: tempValue,
      isEditing: false,
      editingField: ''
    });
    // 提交请求进行修改
    // 获取userId从storage中
    const userId = getStorage("userInfo").userId
    updateUserInfo(userId, this.data.userName, this.data.classesIds[this.data.classesIndex], this.data.nickName, this.data.email, this.data.phonenumber, this.data.sexIndex, '0', 'CourseManagementApplet'); // CourseManagementApplet是应用名称
    // 调用查询个人信息接口
    this.getUserInfo();
  },
  // 取消修改
  cancelEdit() {
    this.getUserInfo();
    this.setData({
      [this.data.editingField]: this.data.tempValue,
      isEditing: false,
      editingField: ''
    });
  },

  onShow: function () {
    this.getUserInfo();
  },

  // 点击退出登录按钮的处理函数
  logout: function () {
    // 调用模态框
    modal({ content: "您确定退出登录吗？" }).then((result) => {
      if (result) {
        // 如果用户点击确定
        // 调用clearStorage函数（假设已经在全局或合适的地方定义）
        clearStorage();
        // 返回上一页面
        wx.navigateBack();
      }
    });
  }
});